import {useContext, useEffect, useReducer, useRef} from 'react';
import {
  Alert,
  Button,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import TimerButton from '../CustomComponents/TimerButton';
import {useNavigation} from '@react-navigation/native';
import TouchableView from '../CustomComponents/TouchableView';
import StorageManager from '../Storage/StorageManager';
import {LoginContext} from '../Stacks/HomeStack';

// Initial Type
type RegisterType = {userId: string; password: string};
// Initial variable
let originalUserId = '';
let originalPassword = '';

const Login = () => {
  const navigation: any = useNavigation();
  type StateType = typeof defaultState;
  type ActionType = {type: string; payload: boolean};
  const reducer = (prevState: StateType, action: ActionType) => {
    switch (action.type) {
      case 'userIdErrorHidden_update':
        return {...prevState, userIdErrorHidden: action.payload};
      case 'identityErrorHidden_update':
        return {...prevState, identityErrorHidden: action.payload};
      case 'disabled_update':
        return {...prevState, disabled: action.payload};
      case 'isPasswordLogin_update':
        return {
          ...prevState,
          isPasswordLogin: action.payload,
          identityErrorHidden: false,
          userIdErrorHidden: false,
        };
      default:
        return prevState;
    }
  };
  const defaultState = {
    // userId: '',
    // password: '',
    disabled: true,
    userIdErrorHidden: false,
    identityErrorHidden: false,
    isPasswordLogin: false,
  };
  const initAction = (initState: StateType) => {
    return initState;
  };
  const [state, dispatch] = useReducer(reducer, defaultState, initAction);
  // Check User ID
  const checkUserId = (inputText: string) => {
    originalUserId = inputText;
    if (inputText.length < 5) {
      dispatch({type: 'userIdErrorHidden_update', payload: false});
    } else {
      dispatch({type: 'userIdErrorHidden_update', payload: true});
    }
  };
  // Check verify code
  const checkVerifyCode = (inputText: string) => {
    if (inputText.length == 6) {
      dispatch({type: 'identityErrorHidden_update', payload: true});
    } else {
      dispatch({type: 'identityErrorHidden_update', payload: false});
    }
  };
  // Check password
  const checkPassword = (inputText: string) => {
    originalPassword = inputText;
    if (inputText.length >= 6) {
      dispatch({type: 'identityErrorHidden_update', payload: true});
    } else {
      dispatch({type: 'identityErrorHidden_update', payload: false});
    }
  };
  // Login button click
  const loginClick = () => {
    StorageManager.readObject<RegisterType>('User')
      .then(([success, value]) => {
        if (success) {
          if (
            value?.userId == originalUserId &&
            value?.password == originalPassword &&
            state.isPasswordLogin
          ) {
            StorageManager.storeValue('Login', '1')
              .then(() => {
                loginState.setLogin(true);
                navigation.goBack();
              })
              .catch(() => {
                Alert.alert('Oops! Login error!');
              });
          } else {
            Alert.alert('Oops! Login error!');
          }
        }
      })
      .catch(() => {
        Alert.alert('Oops! Read storage error!');
      });
  };
  // Password login button click
  const passwordLoginClick = () => {
    userIdInputRef.current?.clear();
    dispatch({type: 'isPasswordLogin_update', payload: !state.isPasswordLogin});
  };
  // Register button click
  const registerClick = () => {
    navigation.navigate('Register');
  };

  useEffect(() => {
    if (state.userIdErrorHidden && state.identityErrorHidden) {
      if (state.disabled) {
        dispatch({type: 'disabled_update', payload: false});
      }
    } else {
      if (!state.disabled) {
        dispatch({type: 'disabled_update', payload: true});
      }
    }
  }, [state.userIdErrorHidden, state.identityErrorHidden]);

  const userIdInputRef = useRef<TextInput>(null);
  const loginState = useContext(LoginContext);

  return (
    <TouchableView>
      <TextInput
        style={styles.userIDInputStyle}
        ref={userIdInputRef}
        placeholder="Please enter your user ID"
        onChangeText={checkUserId}></TextInput>
      <Text style={[styles.errorMessageStyle]}>
        {state.userIdErrorHidden ? '' : 'Please enter your ID correctly!'}
      </Text>
      {state.isPasswordLogin ? (
        <TextInput
          style={styles.passwordInputStyle}
          placeholder="Plesse enter password"
          onChangeText={checkPassword}></TextInput>
      ) : (
        <View style={styles.verifyCodeInputViewStyle}>
          <TextInput
            style={styles.verifyCodeInputStyle}
            placeholder="Plesse enter verify code"
            onChangeText={checkVerifyCode}
            maxLength={6}></TextInput>
          <TimerButton seconds={5} />
        </View>
      )}
      <Text style={[styles.errorMessageStyle, {marginBottom: 50}]}>
        {state.identityErrorHidden
          ? ''
          : state.isPasswordLogin
          ? 'Please enter your password correctly!'
          : 'Please enter verify code correctly!'}
      </Text>
      <Button
        disabled={state.disabled}
        title="Login"
        color="steelblue"
        onPress={loginClick}
      />
      <View style={styles.userActionViewStyle}>
        <TouchableOpacity onPress={passwordLoginClick}>
          <Text style={styles.passwordLoginTextStyle}> Password Login </Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={registerClick}>
          <Text style={styles.registerTextStyle}> Register </Text>
        </TouchableOpacity>
      </View>
    </TouchableView>
  );
};

const styles = StyleSheet.create({
  userIDInputStyle: {
    marginTop: 150,
    marginLeft: 30,
    marginRight: 30,
    height: 40,
    borderWidth: 1,
    borderRadius: 5,
    borderColor: '#ddd',
    fontSize: 15,
    padding: 5,
  },
  verifyCodeInputViewStyle: {
    marginLeft: 30,
    marginRight: 30,
    flexDirection: 'row',
    alignItems: 'center',
  },
  verifyCodeInputStyle: {
    flex: 1,
    marginRight: 15,
    height: 40,
    borderWidth: 1,
    borderRadius: 5,
    borderColor: '#ddd',
    fontSize: 15,
    padding: 5,
  },
  passwordInputStyle: {
    marginLeft: 30,
    marginRight: 30,
    height: 40,
    borderWidth: 1,
    borderRadius: 5,
    borderColor: '#ddd',
    fontSize: 15,
    padding: 5,
  },
  errorMessageStyle: {
    marginTop: 5,
    marginBottom: 5,
    marginLeft: 30,
    marginRight: 30,
    height: 20,
    fontSize: 13,
    color: 'lightcoral',
  },
  userActionViewStyle: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 100,
    marginLeft: 60,
    marginRight: 60,
    height: 30,
  },
  passwordLoginTextStyle: {
    fontSize: 15,
    color: 'steelblue',
  },
  registerTextStyle: {
    fontSize: 15,
    color: 'steelblue',
  },
});

export default Login;
